var Config = function() {
    this.size = 50;
    this.flagColor = '#029318';
    this.nextColor = '#018174';
    this.errorColor = '#591831';
}

var Draw = function(ctx) {
    this.drawBox = function(size) {
        for (let i=0; i<=col; i++) {
            ctx.moveTo(i * size, 0);
            ctx.lineTo(i * size, size * size)
            ctx.stroke();
        }
        for (let i=0; i<=row + 1; i++) {
            ctx.moveTo(0, i * size);
            ctx.lineTo(size * size, i * size)
            ctx.stroke();
        }
	}
    this.initNums = function() {
        for (let i=0; i<row; i++) {
            ctx.font = "bold 30px Arial";
            ctx.fillStyle = "#000000";
            for (let j=1; j<=col; j++) {
                let coord = indexToCoord(j - 1, i);
                if (j > 4) {
                    ctx.font = "bold 20px Arial";
                    // ctx.fillStyle = "red";
                    ctx.strokeText(nums[i][j], coord[0], coord[1]);
                    continue;
                }
                ctx.fillText(nums[i][j], coord[0], coord[1]);
            }
        }
    }
}
Draw.prototype.setColor = function(i, j, color) {
    let coord = indexToCoord(i, j);
    ctx.beginPath();
    ctx.arc(coord[0], coord[1], config.size / 10, 0, 2 * Math.PI);
    ctx.fillStyle = color;
    ctx.fill();
    ctx.stroke();
}
Draw.prototype.drawLine = function (sourceIndex, targetIndex, color) {
    let source = indexToCoord(sourceIndex[0], sourceIndex[1]);
    let target = indexToCoord(targetIndex[0], targetIndex[1]);
    ctx.moveTo(target[0], target[1]);
    ctx.lineTo(source[0], source[1]);
    ctx.lineWidth = 2;
    ctx.strokeStyle = color;
    ctx.stroke();
}

var canvas = document.getElementById("box");
var ctx = canvas.getContext("2d");
var config = new Config();
var draw = new Draw(ctx);

canvas.width = config.size * col;
canvas.height = config.size * (row + 1);
draw.drawBox(config.size);
draw.initNums();

canvas.addEventListener("click", function(event) {
    let rect = canvas.getBoundingClientRect();
    let index = coordToIndex(event.clientY, event.clientX);
    let i = index[0];
    let j = index[1];
    draw.setColor(j, i, "red");
    if (sourceCoord.length != 0) {
        let sourceIndex = sourceCoord[sourceCoord.length - 1];
        draw.drawLine([sourceIndex[1], sourceIndex[0]], [j, i], config.flagColor);
    }
    sourceCoord.push(index);
});
function coordToIndex(x, y) {
    let j = parseInt(y / config.size);
    let i = parseInt(x / config.size);
    return [i, j];
}
function indexToCoord(i, j) {
    let x = parseInt((i + 1) * config.size - (config.size / 1.5));
    let y = parseInt((j + 1) * config.size - (config.size / 3));
    return [x, y];
}
